import jwt from 'jsonwebtoken';
import { SERVER_CONFIG } from '../config.js';

export const authenticateToken = (req, res, next) => {
  const authHeader = req.headers.authorization;
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ message: '未提供授权令牌' });
  }

  jwt.verify(token, SERVER_CONFIG.JWT.SECRET, (err, user) => {
    if (err) {
      console.error('Token验证失败:', err);
      return res.status(403).json({ message: '令牌无效或已过期' });
    }

    req.user = user;
    next();
  });
};

export const optionalAuthentication = (req, res, next) => {
  const authHeader = req.headers.authorization;
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    req.user = null;
    return next();
  }

  jwt.verify(token, SERVER_CONFIG.JWT.SECRET, (err, user) => {
    if (err) {
      req.user = null;
    } else {
      req.user = user;
    }
    next();
  });
}; 